package com.example.jetpack.learn

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.jetpack.R

class MyPagingDataAdapter : PagingDataAdapter<Item,MyViewHolder>(mDiffUtil) {

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val item = getItem(position)
        item?.let {
            holder.tv.text = "${it.id}${it.name}"
        }?:let {
            holder.tv.text = "数据加载中..."
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item,parent,false)
        return MyViewHolder(view)
    }

}

class MyViewHolder(view: View): RecyclerView.ViewHolder(view){
    val tv : TextView

    init {
        tv = view.findViewById(R.id.tv)
    }

}

private val mDiffUtil  = object: DiffUtil.ItemCallback<Item>(){
    //相当于检查唯一性
    override fun areItemsTheSame(oldItem: Item, newItem: Item): Boolean {
        return oldItem.id == newItem.id
    }
    //检查是否有一样的数据
    override fun areContentsTheSame(oldItem: Item, newItem: Item): Boolean {
        return oldItem.id == newItem.id
    }

}